/**
 * 
 */
package org.dse.proc;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dse.util.Constants;

/**
 * This class works as an utility. It wraps the logic of getting the task
 * content from the task file. It just reads the file and store the task content
 * in an list. It also provides interfaces for the outside to access the list to
 * get the task content.
 * 
 * @author zhangchen
 * 
 */
public class TaskGetter {

	private String taskFile;

	private List<String> updateFiles;// the list containing the update raw
										// files

	private List<String> deleteUrls;// the list containing the urls to be
									// deleted

	private static final Log log = LogFactory.getLog(TaskGetter.class);

	/**
	 * The constructor. Initialize the list.
	 * 
	 * @param taskFile
	 *            the file containing the task content, including the update raw
	 *            files and deleted urls
	 */
	public TaskGetter(String taskFile) {
		this.taskFile = taskFile;
		this.updateFiles = new ArrayList<String>();
		this.deleteUrls = new ArrayList<String>();
	}

	/**
	 * The logic about getting task from the task file. It just reads the file
	 * from start to end. According to the rule, store the data to the list.
	 */
	public void getTaskFromFile() {
		try {
			BufferedReader reader = new BufferedReader(new FileReader(taskFile));
			String strLine = null;

			// the content of update raw files section
			while ((strLine = reader.readLine()) != null) {
				if (strLine.equals(Constants.CREATE_INDEX_FILE))
					break;
			}

			// the content of update raw files section
			while ((strLine = reader.readLine()) != null && !strLine.equals("")) {
				updateFiles.add(strLine);
			}

			// the start of deleted urls section
			while ((strLine = reader.readLine()) != null) {
				if (strLine.equals(Constants.DELETED_URL))
					break;
			}

			// the content of deleted urls section
			while ((strLine = reader.readLine()) != null && !strLine.equals("")) {
				deleteUrls.add(strLine);
			}

			reader.close();

		} catch (FileNotFoundException e) {
			System.err.println("There is no task file to read.");
			log.error("There is no task file to read.", e);
		} catch (IOException e) {
			System.err.println("Error in reading the file.");
			log.error("Error in reading the file.", e);
		}
	}

	/**
	 * Return the update raw files list.
	 * 
	 * @return a list containing all the raw files name
	 */
	public List<String> getUpdateFiles() {
		return updateFiles;
	}

	/**
	 * Return the deleted urls list.
	 * 
	 * @return a list containing all the deleted urls
	 */
	public List<String> getDeleteUrls() {
		return deleteUrls;
	}
}
